<template>
  <div class="flex flex-row gap-[32px]">
    <div class="flex flex-col w-[100px] border border-solid border-black">
      <div class="flex flex-row justify-center">
        <div :class="{ 'text-red-500': downKey.includes('KeyW') }">W</div>
      </div>
      <div class="flex flex-row justify-between">
        <div :class="{ 'text-red-500': downKey.includes('KeyA') }">A</div>
        <div :class="{ 'text-red-500': downKey.includes('KeyD') }">D</div>
      </div>
      <div class="flex flex-row justify-center">
        <div :class="{ 'text-red-500': downKey.includes('KeyS') }">S</div>
      </div>
    </div>
    <div class="flex flex-col w-[150px] border border-solid border-black">
      <div class="flex flex-row justify-start gap-[40px] pl-[60px]">
        <div :class="{ 'text-red-500': downKey.includes('KeyI') }">I</div>
        <div :class="{ 'text-red-500': downKey.includes('KeyO') }">O</div>
      </div>
      <div class="flex flex-row justify-start pl-[20px]">
        <div :class="{ 'text-red-500': downKey.includes('KeyU') }">U</div>
      </div>
      <div class="flex flex-row justify-start gap-[40px]">
        <div :class="{ 'text-red-500': downKey.includes('KeyH') }">H</div>
        <div :class="{ 'text-red-500': downKey.includes('KeyJ') }">J</div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onBeforeUnmount, onMounted, ref, toRaw, toValue, watch } from 'vue';

const downKey = ref([])
const command = ref()
const $emits = defineEmits(['command'])

const onKeyDown = e => {
  const downKeyValue = toValue(downKey)
  if (downKeyValue.includes(e?.code)) {
    return
  }

  downKey.value.push(e?.code)
  command.value = {
    type: 'keydown',
    code: e?.code,
    allCodes: toRaw(downKey.value)
  }
}

const onKeyUp = e => {
  const downKeyValue = toValue(downKey)

  const index = downKeyValue.findIndex(k => k === e.code)
  if (index >= 0) {
    downKey.value.splice(index, 1)
  }
  command.value = {
    type: 'keyup',
    code: e?.code,
    allCodes: toRaw(downKey.value)
  }
}

watch(command, val => {
  $emits('command', val)
}, {
  deep: true
})

onMounted(() => {
  document.addEventListener('keydown', onKeyDown)
  document.addEventListener('keyup', onKeyUp)
})

onBeforeUnmount(() => {
  document.removeEventListener('keypress', onKeyDown)
  document.removeEventListener('keyup', onKeyUp)
})
</script>
<style lang="scss" scoped></style>